import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

class FloatButton extends StatefulWidget {
  final Widget child;
  Offset offset;

  FloatButton({Key key, this.child, this.offset}) : super(key: key);

  @override
  _FloatButtonState createState() => _FloatButtonState();

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(DiagnosticsProperty<Widget>('child', child));
  }
}

class _FloatButtonState extends State<FloatButton> {
  // Offset offset = widget.offset ?? Offset(10, kToolbarHeight + 100);

  Offset _calOffset(Size size, Offset offset, Offset nextOffset) {
    double dx = 0;
    //水平方向偏移量不能小于0不能大于屏幕最大宽度
    if (offset.dx + nextOffset.dx <= 0) {
      dx = 0;
    } else if (offset.dx + nextOffset.dx >= (size.width - 50)) {
      dx = size.width - 50;
    } else {
      dx = offset.dx + nextOffset.dx;
    }
    double dy = 0;
    //垂直方向偏移量不能小于0不能大于屏幕最大高度
    if (offset.dy + nextOffset.dy >= (size.height - 100)) {
      dy = size.height - 100;
    } else if (offset.dy + nextOffset.dy <= kToolbarHeight) {
      dy = kToolbarHeight;
    } else {
      dy = offset.dy + nextOffset.dy;
    }
    return Offset(
      dx,
      dy,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Positioned(
      left: widget.offset.dx,
      top: widget.offset.dy,
      child: GestureDetector(
          onPanUpdate: (detail) {
            setState(() {
              widget.offset = _calOffset(
                  MediaQuery.of(context).size, widget.offset, detail.delta);
            });
          },
          onPanEnd: (detail) {},
          child: widget.child),
    );
  }
}
